﻿using CaseManagerLibrary.Log;
using PSDLib.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static PSDLib.Download.DPSDK;

namespace PSDLib.Download
{
    public class DH8900DownloadServer : IDownloadServer
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public ILog Logger { get; set; }
        public string ServerIP { get; set; }
        public int ServerPort { get; set; }
        public string ServerUser { get; set; }
        public string ServerPassword { get; set; }

        private bool online = false;
        private static object lock_online = new object();
        List<ChannelInfo> channelList = new List<ChannelInfo>();
        public bool Online
        {
            get
            {
                lock (lock_online)
                {
                    return online;
                }
            }
            set
            {
                lock (lock_online)
                {
                    online = value;
                }
            }
        }

        public event EventHandler OnDisConnect;
        public event EventHandler OnReConnect;

        public DH8900DownloadServer()
        {
            Logger = new ConsoleLog();
            Logger.BringToFront = false;
        }

        public void Cleanup()
        {
            try
            {
                IntPtr result1 = DPSDK_Destroy(nPDLLHandle);
                IntPtr result2 = DPSDK_UnitExt();

                downlaoderList.Clear();

                if (result1 == (IntPtr)0 && result2 == (IntPtr)0)
                {
                    Logger.Info("销毁DPSDK成功");
                }
                else
                {
                    //return err
                    Logger.Info("销毁DPSDK失败");
                }
            }
            catch { }
        }

        public IDownloader CreateDownload(dl_files file)
        {
            //创建大华存储设备下载器
            var dh_downloader = new DH_8900_Downloader();
            dh_downloader.nPDLLHandle = nPDLLHandle;
            dh_downloader.Id = file.id;
            dh_downloader.Logger = Logger;
            dh_downloader.DownloadServer = this;

            return dh_downloader;
        }

        public List<ChannelInfo> GetChannelList()
        {
            channelList.Clear();

            var xml = GetGroupXml();

            if (xml != null)
            {
                var devices = xml.SelectNodes("Organization/Devices/Device[contains(@name,'审讯主机')]");

                foreach (System.Xml.XmlNode device in devices)
                {
                    var cameraList = device.SelectNodes("UnitNodes[@streamType]/Channel");

                    foreach (System.Xml.XmlNode camera in cameraList)
                    {
                        var ch = new ChannelInfo();
                        ch.Id = camera.Attributes["id"].Value;
                        ch.Name = camera.Attributes["name"].Value;
                        channelList.Add(ch);
                    }
                }

                channelList.Sort();
            }

            return channelList;
        }

        public System.Xml.XmlDocument GetGroupXml()
        {
            string xml_path = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "DH8900.xml");
            IntPtr nGroupLen = IntPtr.Zero;
            IntPtr result = DPSDK_LoadDGroupInfo(nPDLLHandle, ref nGroupLen, (IntPtr)60000);
            if (result == (IntPtr)0)
            {
                byte[] szGroupStr = new byte[(int)nGroupLen + 1];
                result = DPSDK_GetDGroupStr(nPDLLHandle, ref szGroupStr[0], nGroupLen, (IntPtr)10000);
                if (result == IntPtr.Zero)
                {
                    try
                    {
                        if (System.IO.File.Exists(xml_path))
                        {
                            System.IO.File.Delete(xml_path);
                        }
                        System.IO.FileStream fs = new System.IO.FileStream(xml_path, System.IO.FileMode.Create);
                        fs.Write(szGroupStr, 0, (int)nGroupLen);
                        fs.Flush();
                        fs.Close();

                        //string tree_str = System.Text.Encoding.UTF8.GetString(szGroupStr);
                        //System.Xml.XmlDocument tree_xml = new System.Xml.XmlDocument();
                        //tree_xml.LoadXml(tree_str);
                        //tree_xml.Save(xml_path);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("DH8900DownloadServer.GetChannelList异常：" + ex.Message);
                    }
                }
            }

            System.Xml.XmlDocument xml = null;

            if (System.IO.File.Exists(xml_path))
            {
                xml = new System.Xml.XmlDocument();
                xml.Load(xml_path);
            }

            return xml;
        }

        public string GetLastError()
        {
            return "";
        }

        private bool resetting = false;
        public IntPtr nPDLLHandle;

        public bool Init()
        {
            bool success = false;

            IntPtr result1 = DPSDK.DPSDK_Create(dpsdk_sdk_type_e.DPSDK_CORE_SDK_SERVER, ref this.nPDLLHandle);//初始化数据交互接口
            IntPtr result2 = DPSDK.DPSDK_InitExt();//初始化解码播放接口
            if (result1 == (IntPtr)0 && result2 == (IntPtr)0)
            {
                success = true;
                Logger.Info("【" + Name + "】初始化DPSDK成功");
            }
            else
            {
                //return err
                success = false;
                Logger.Error("【" + Name + "】初始化DPSDK失败");
            }
            IntPtr result = (IntPtr)10;
            //设置日志路径，运行程序自动在D盘生成日志
            //string log_path = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "PSD", "Log");
            //result = DPSDK_SetLog(nPDLLHandle, dpsdk_log_level_e.DPSDK_LOG_LEVEL_DEBUG, log_path, false, false);
            ////崩溃自动生成dmp文件
            //result = DPSDK_StartMonitor(nPDLLHandle, "DPSDK_Dump");
            IntPtr pUser = default(IntPtr);

            fDownLoadProcess = DownloadProgressCallback;
            result = DPSDK.DPSDK_SetDownloadProgressCallback(nPDLLHandle, fDownLoadProcess, pUser);

            fDownLoadFinish = DownloadFinishedCallback;
            result = DPSDK.DPSDK_SetDownloadFinishedCallback(nPDLLHandle, fDownLoadFinish, pUser);

            return success;
        }

        public bool Login()
        {
            bool success = false;

            downlaoderList.Clear();

            Login_Info_t loginInfo = new Login_Info_t();
            loginInfo.szIp = ServerIP;
            loginInfo.nPort = (uint)ServerPort;
            loginInfo.szUsername = ServerUser;
            loginInfo.szPassword = ServerPassword;
            loginInfo.nProtocol = dpsdk_protocol_version_e.DPSDK_PROTOCOL_VERSION_II;
            loginInfo.iType = 1;

            //#if DEBUG
            //            Online = true;
            //            success = true;
            //            Logger.Info("登录存储设备成功");
            //#else
            IntPtr result = DPSDK_Login(this.nPDLLHandle, ref loginInfo, (IntPtr)10000);
            if (result == (IntPtr)0)
            {
                Online = true;
                success = true;
                Logger.Info("登录存储设备成功");
            }
            else
            {
                Online = false;
                success = false;
                Logger.Error("登录存储设备失败：" + result.ToString());
            }
            //#endif
            return success;
        }

        public void Logout()
        {
            try
            {
                foreach (var downloader in downlaoderList)
                {
                    downloader.Stop();
                }

                downlaoderList.Clear();

                IntPtr result = DPSDK_Logout(nPDLLHandle, (IntPtr)10000);

                Logger.Info("登出存储设备：" + result.ToString());
            }
            catch
            { }
            finally
            {
                Online = false;
            }
        }

        public bool ReLogin()
        {
            bool success = false;

            resetting = true;

            Cleanup();

            if (Init())
            {
                success = Login();
            }
            else
            {
                success = false;
            }

            resetting = false;

            return success;
        }

        public void ResetSessionInfo(IDownloader downloader)
        {
            if (downloader != null)
            {
                downloader.ResetSessionInfo(nPDLLHandle);
            }
        }

        public List<DH_8900_Downloader> downlaoderList = new List<DH_8900_Downloader>();

        public IntPtr DownloadProgressCallback(IntPtr nPDLLHandle, int downloadSeq, int position, IntPtr pUserParam)
        {
            if (position >= 0 && position <= 100)
            {
                var downloader = downlaoderList.Where(t => t.nPDLLHandle.Equals(nPDLLHandle) && t.downloadSeq == downloadSeq).FirstOrDefault();
                if (downloader != null)
                {
                    downloader.UpdateProgress(position);
                }
            }

            return (IntPtr)0;
        }

        public IntPtr DownloadFinishedCallback(IntPtr nPDLLHandle, int downloadSeq, IntPtr pUserParam)
        {
            var downloader = downlaoderList.Where(t => t.nPDLLHandle.Equals(nPDLLHandle) && t.downloadSeq == downloadSeq).FirstOrDefault();
            if (downloader != null)
            {
                downloader.FinishDownload(true);

                // downlaoderList.Remove(downloader);
            }

            return (IntPtr)0;
        }
    }


}
